<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { useUserStore } from '@/stores/userStore'

const isRegister = ref(false)
const isForgotPassword = ref(false)
const form = ref()
const userStore = useUserStore()
const router = useRouter()

// 注册、登录、忘记密码的表单数据
const formModel = ref({
  username: '',
  password: '',
  rePassword: '',
  newPassword: '',
  confirmNewPassword: '',
  role: '',
  email: ''
})

// 整个表单的校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 10, message: '用户名必须是5-10位的字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符',
      trigger: 'blur'
    }
  ],
  repassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15的非空字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== formModel.value.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  // 新增邮箱校验
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符',
      trigger: 'blur'
    }
  ],
  confirmNewPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15的非空字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== formModel.value.newPassword) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 登录模块
const login = async () => {
  await form.value.validate()

  try {
    const response = await axios.get('http://localhost:3000/users', {
      params: {
        username: formModel.value.username,
        password: formModel.value.password
      }
    })

    if (response.data.length > 0) {
      const user = response.data[0]
      userStore.setUser(user)
      ElMessage.success('登录成功')
      localStorage.setItem('isLoggedIn', 'true')
      localStorage.setItem('userRole', user.role)

      if (user.role === 'admin') {
        router.push('/admin')
      } else if (user.role === 'buyer') {
        router.push('/main/home')
      } else if (user.role === 'seller') {
        router.push('/main/home')
      }
    } else {
      ElMessage.error('用户名或密码错误')
    }
  } catch (error) {
    ElMessage.error('登录失败，请重试')
    console.error(error)
  }
}

// 注册模块
const register = async () => {
  await form.value.validate()

  try {
    // 检查用户名是否已存在
    const existingUsers = await axios.get('http://localhost:3000/users', {
      params: { username: formModel.value.username }
    })

    if (existingUsers.data.length > 0) {
      return ElMessage.error('用户名已存在')
    }

    // 创建新用户
    const newUser = {
      username: formModel.value.username,
      password: formModel.value.password,
      email: formModel.value.email,
      role: formModel.value.role,
      registeredAt: new Date().toISOString().split('T')[0],
      status: 'active'
    }

    // 使用 POST 请求将新用户添加到 db.json
    await axios.post('http://localhost:3000/users', newUser)

    ElMessage.success('注册成功')
    isRegister.value = false
  } catch (error) {
    ElMessage.error('注册失败，请重试')
    console.error(error)
  }
}

// 忘记密码模块，重置密码
const resetPassword = async () => {
  await form.value.validate()

  try {
    // 查找用户
    const response = await axios.get('http://localhost:3000/users', {
      params: { username: formModel.value.username }
    })

    if (response.data.length === 0) {
      return ElMessage.error('用户名不存在')
    }

    // 更新用户密码
    await axios.patch(`http://localhost:3000/users/${response.data[0].id}`, {
      password: formModel.value.newPassword
    })

    ElMessage.success('密码重置成功')
    isForgotPassword.value = false
  } catch (error) {
    ElMessage.error('密码重置失败，请重试')
    console.error(error)
  }
}
</script>

<template>
  <div class="login-page">
    <!-- :model : 单向数据绑定，将表单数据传递给表单组件进行校验 -->
    <div class="form">
      <el-form :model="formModel" :rules="rules" ref="form" size="large" autocomplete="off" v-if="isRegister">
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input v-model="formModel.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="formModel.password" :prefix-icon="Lock" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input v-model="formModel.repassword" :prefix-icon="Lock" type="password" placeholder="请再次输入密码"></el-input>
        </el-form-item>
        <el-form-item prop="role">
          <el-select v-model="formModel.role" placeholder="请选择角色">
            <el-option label="买家" value="buyer"></el-option>
            <el-option label="卖家" value="seller"></el-option>
            <el-option label="管理员" value="admin"></el-option>
          </el-select>
        </el-form-item>
        <!-- 新增邮箱 -->
        <el-form-item prop="email">
          <el-input v-model="formModel.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item>
          <el-button class="button" @click="register" type="danger" auto-insert-space>
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>
      <el-form :model="formModel" :rules="rules" ref="form" size="large" autocomplete="off"
        v-else-if="!isForgotPassword">
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input v-model="formModel.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="formModel.password" name="password" :prefix-icon="Lock" type="password"
            placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="info" :underline="false" @click="isForgotPassword = true">忘记密码？</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button @click="login" class="button" type="danger" auto-insert-space>登录</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
      <el-form v-bind:model="formModel" :rules="rules" ref="form" size="large" autocomplete="off" v-else>
        <el-form-item>
          <h1>忘记密码</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input v-model="formModel.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="newPassword">
          <el-input v-model="formModel.newPassword" :prefix-icon="Lock" type="password" placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item prop="confirmNewPassword">
        </el-form-item>
        <el-form-item>
          <el-button class="button" @click="resetPassword" type="danger" auto-insert-space>
            重置密码
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isForgotPassword = false">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.login-page {
  margin: 0;
  padding: 0;
  height: 100vh;
  width: 100vw;
  background-image: url('public/d070fbc2-8c31-4306-8677-c2ad566f26e5.jpg');
  /* 引用背景图片 */
  background-size: cover;
  /* 宽度撑满视角，自动调整高度 */
  background-position: center;
  /* 背景图片居中 */
  background-repeat: no-repeat;
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  inset: 0;
}

.form {
  display: flex;
  flex-direction: column;
  user-select: none;
  width: 320px;
  background-color: rgba(255, 255, 255, 0.9);
  /* 增加背景色透明度，防止背景遮挡 */
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  z-index: 1;
  /* 确保表单在背景之上 */
}

.title {
  margin: 0 auto;
}

.button {
  width: 100%;
}

.flex {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
</style>